package org.example;

import java.util.HashSet;
import java.util.Set;

public class Test2 {
    //leetcode 349 两个数组的交集 https://leetcode.cn/problems/intersection-of-two-arrays/
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<>(), set2 = new HashSet<>();
        for (int n : nums1) {
            if (!set1.contains(n)) set1.add(n);
        }
        for (int n : nums2) {
            if (set1.contains(n)) set2.add(n);
        }

        //将set转为数组方法一
        int[] ret = new int[set2.size()];
        int index = 0;
        for (Integer n : set2) {
            ret[index++] = n;
        }
        return ret;

        //方法二: 通过流的方式
        //return set2.stream().mapToInt(x -> x).toArray();
    }
}
